package com.store.app.broadcast;


import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import java.io.File;

public class CompleteService extends Service {
	private DownloadManager manager;
	private DownloadCompleteReceiver receiver;
	private String url;
	private String DOWNLOADPATH = "/diandong/apk/";
	private void initDownManager() {
		manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
		receiver = new DownloadCompleteReceiver();
		DownloadManager.Request down = new DownloadManager.Request(Uri.parse(url));
		down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
				| DownloadManager.Request.NETWORK_WIFI);
		down.setAllowedOverRoaming(false);
		MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
		String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
		down.setMimeType(mimeString);
		down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
		down.setVisibleInDownloadsUi(true);
		down.setDestinationInExternalPublicDir(DOWNLOADPATH,"diandong.apk");
		down.setTitle("店东助手");
		manager.enqueue(down);
		registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		url = intent.getStringExtra("downloadurl");
		String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ DOWNLOADPATH + "diandong.apk";
		File file = new File(path);
		if(file.exists()){
			boolean  isdel=deleteFile(path);
			Log.i("mylog", "删除旧的apk");
		}
		try{
			initDownManager();
		}catch (Exception e){
			e.printStackTrace();
		}
//        return super.onStartCommand(intent, flags, startId);
		return Service.START_NOT_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}

	@Override
	public void onDestroy() {
		if (receiver != null)
			unregisterReceiver(receiver);
		super.onDestroy();
	}

	class DownloadCompleteReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {

			if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
				long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
				if(manager.getUriForDownloadedFile(downId)!=null){
//                    installAPK(manager.getUriForDownloadedFile(downId),context);
					Log.i("mylog", "aa");
					installAPK(context);
				}else{
					Toast.makeText(context,"下载失败",Toast.LENGTH_SHORT).show();
				}
				CompleteService.this.stopSelf();
			}
		}



		private void installAPK(Context context) {
			File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ DOWNLOADPATH + "diandong.apk");
			if(file.exists()){
				openFile(file,context);
			}else{
				Toast.makeText(context,"下载失败",Toast.LENGTH_SHORT).show();
			}
		}
	}


	public void openFile(File var0, Context var1) {
		Intent var2 = new Intent();
		var2.addFlags(268435456);
		var2.setAction("android.intent.action.VIEW");
		String var3 = getMIMEType(var0);
		var2.setDataAndType(Uri.fromFile(var0), var3);
		try {
			var1.startActivity(var2);
		} catch (Exception var5) {
			var5.printStackTrace();
			Toast.makeText(var1, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
		}

	}
	public String getMIMEType(File var0) {
		String var1 = "";
		String var2 = var0.getName();
		String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
		var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
		return var1;
	}
	public boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}
}
